package com.pignest.hotel.ui.income;

import java.util.Date;
import java.util.List;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;



import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Living;
import com.pignest.hotel.beans.ProtocolUnit;
import com.pignest.hotel.beans.TbLiveGoodsBorrow;
import com.pignest.hotel.definition.InComeItemType;
import com.pignest.hotel.definition.LivingState;
import com.pignest.hotel.service.IncomeService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.system.InComeUtil;
import com.pignest.hotel.system.Logic;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.MoneyUtil;
import com.pignest.hotel.util.UIUtils;

public class HangUpWindow extends Window implements EventListener {

	/**
	 * 挂账
	 */
	private static final long serialVersionUID = 6186731279845640743L;
	private IncomeService incomeService;
	/***合计项***/
	private Label aStorage;
	private Label aUsed;
	private Label aAvailable;
	private Label aPayed;
	private Label aLivingTime;
	private Label aLeavingTime;
	private Textbox aAddPay;//所有加收金额
	
	private Listbox livingsListbox;
	private Listbox aListbox;
	private Radiogroup sGroup;
	private Listbox addPayList;
	
	private Textbox rRoomName;
	private Textbox rCustormName;
	private Textbox rRemark;
	
	private Date earlyTime;
	private Date checkTime;
	private Button okBtn;
	
	private Listbox protocolUnitList;
	private Label hProtocolUnit;
	private Label maxPrice;
	private Label hangUpprice;
	
	private List<Living> selectLive;//选择的入住
	public HangUpWindow(){
		incomeService =Services.getIncomeService();
		addEventListener("onCreate", this);
	}
	@Override
	public void onEvent(Event event) throws Exception {
		// TODO Auto-generated method stub
		if ("onCreate".equals(event.getName())) {
			 aStorage=(Label)getFellow("aStorage");
			 aUsed=(Label)getFellow("aUsed");
			 aPayed=(Label)getFellow("aPayed");
			 aAvailable=(Label)getFellow("aAvailable");
			 aLivingTime=(Label)getFellow("aLivingTime");
			 aLeavingTime=(Label)getFellow("aLeavingTime");
			 aAddPay=(Textbox)getFellow("aAddPay");
			 
			 livingsListbox=(Listbox)getFellow("livingsListbox");
			 aListbox=(Listbox)getFellow("aListbox");
			 sGroup=(Radiogroup)getFellow("sGroup");
			 addPayList=(Listbox)getFellow("addPayList");
			 
			 rRoomName=(Textbox)getFellow("rRoomName");
			 rCustormName=(Textbox)getFellow("rCustormName");
			 rRemark=(Textbox)getFellow("rRemark");
			 okBtn=(Button)getFellow("okBtn");
			 
			 protocolUnitList=(Listbox)getFellow("protocolUnitList");
			 hProtocolUnit=(Label)getFellow("hProtocolUnit");
			 maxPrice=(Label)getFellow("maxPrice");
			 hangUpprice=(Label)getFellow("hangUpprice");
			 sGroup.addEventListener(Events.ON_CHECK, new EventListener(){
				   public void onEvent(Event event) {
					   queryStatic();
				   }
			   });
			 addPayList.addEventListener(Events.ON_SELECT, new EventListener(){
				   public void onEvent(Event event) {
					   selectSingleAddPay();
				   }
			   });
			 init();
		}
	}
	public void init(){
		initLivingList();
		initAddPay();
		
		//initAllLivingLabel();
		
		selectSingleAddPay();
		//initLivingList();
		queryStatic();
		queryProtocolUnit(null,null);
	}
	
	//初始化加收情况
	public void initAddPay()
	{
		int add=Logic.getLivingAdditionalTime(this.getEarlyTime(),this.getCheckTime(),true);
		UIUtils.setSelectedItem(addPayList,String.valueOf(add));
	}
	//选择入住加收情况
	public void selectSingleAddPay()
	{
		String v =UIUtils.getSelectedValue(addPayList);
		int add =Integer.valueOf(v);
		InComeUtil.countInComeAll(selectLive, aStorage, aUsed, aPayed, aAvailable, aAddPay, add);
	}
	public void initLivingList()
	{
		livingsListbox.getItems().clear();
		selectLive=incomeService.queryBySelf(selectLive);
		int index=0;
		for(final Living l:selectLive)
		{
			if(index==0){
				setEarlyTime(l.getLiveTime());
				aLivingTime.setValue(DateUtil.toString(l.getLiveTime(), DateUtil.HOTEL_DEFAULT_FORMAT));
			}
			 Listitem listitem = new Listitem();
			 listitem.setValue(l);
			 listitem.setParent(livingsListbox);
			 listitem.appendChild(new Listcell(String.valueOf(index+1)));
			 listitem.appendChild(new Listcell(l.getRoom().getName()));
			 listitem.appendChild(new Listcell(l.getCustormName()));
			 listitem.appendChild(new Listcell(MoneyUtil.toString(l.getAdjustPrice())));
			 listitem.appendChild(new Listcell(DateUtil.toString(l.getLiveTime(), DateUtil.HOTEL_DEFAULT_FORMAT)));
			 listitem.appendChild(new Listcell(LivingState.valueOf(l.getLiveState()).getDisplayName()));
			 listitem.addEventListener(Events.ON_CLICK, new EventListener(){
				   public void onEvent(Event event) {
					   viewSingleRemark(l);
				   }
			   });
			 index++;
		}
		setCheckTime(new Date());
		aLeavingTime.setValue(DateUtil.currentDateToString(DateUtil.HOTEL_DEFAULT_FORMAT));
	}
	public void viewSingleRemark(Living l)
	{
		rRoomName.setValue(l.getRoom().getName());
		rCustormName.setValue(l.getCustormName());
		rRemark.setValue(l.getRemark());
		if(l.getProtocolUnit()!=null){
			hProtocolUnit.setValue(l.getProtocolUnit().getCompany());
		}else
			hProtocolUnit.setValue("");
	}
	public void queryStatic()
	{
		String s =sGroup.getSelectedItem().getValue();
		aListbox.getItems().clear();
		List sl =null;
		if(s.equals("true"))
		    sl =incomeService.queryAccStaticByMulLiving(selectLive, true);
		else
			sl=incomeService.queryAccStaticByMulLiving(selectLive, false);
		if(sl==null)
			return;
		for(int i=0;i<sl.size();i++)
		{
			Object []o =(Object[])sl.get(i);
			String value =(String)o[1];
			String name ="";
			if(s.equals("false"))
			   name =InComeItemType.valueOf(value).getName();
			else
				name=value;
			Long d=(Long)o[0];
			Listitem listitem = new Listitem();
			listitem.setParent(aListbox);
			listitem.appendChild(new Listcell(MoneyUtil.toString(d)));
			listitem.appendChild(new Listcell(name));
		}
	}
	public void hangUp()
	{
		if(!Hotel.onDuty()){
			UIUtils.alert("对不起你还未值班,不能操作此业务 !");
			return ;
		}
		String unitId =(String)UIUtils.getSelectedValue(protocolUnitList);
		if(unitId==null){
			UIUtils.alert("请选择协议单位!");
			return ;
		}
		ProtocolUnit unit =incomeService.get(ProtocolUnit.class,unitId);
		
		List<Living> curList =incomeService.queryBySelf(selectLive);
		if(!incomeService.isCheckedOut(curList)){
			return ;
		}
		if(!isNoBorrow(curList)){
			if(UIUtils.confirm("有未归还物品是否要继续挂账!")){
				
			}else
			{
				return ;
			}
		}
		StringBuffer msg = new StringBuffer();
		StringBuffer rMsg = new StringBuffer();//存放备注信息
		msg.append("挂账协议单位:").append(unit.getCompany()).append("\n");
		String rUnion="";
		rMsg.append(getAutoLivingReMark(curList));
		if(selectLive.size()>1){
			rUnion="多人";
			msg.append("操作：").append(rUnion).append("\n");
			msg.append("房间:\n").append(rMsg.toString()).append("\n");
		}else{
			rUnion="单人";
			msg.append("操作:").append(rUnion).append("\n");
			msg.append("房间:").append(rMsg.toString()).append("\n");
		}
		int iPayed =incomeService.countAllConsumsPayed(selectLive, true);//已付
		int iUsed=incomeService.countAllConsumsUsed(selectLive, true);//已消费;//总消费
		String sAddpay =aAddPay.getValue();
		String v =UIUtils.getSelectedValue(addPayList);
		String vLable =UIUtils.getSelectedLable(addPayList);
		int add =Integer.valueOf(v);
		int centAddpay =Utils.toPrice(sAddpay);
		if(add!=0){
			String sAddPayName =(String)UIUtils.getSelectedLable(addPayList);
			  msg.append("加收：").append(sAddPayName).append("\n");
			  msg.append("加收金额:").append(Utils.toPrice(centAddpay)).append("\n");  
		}
		int storage=incomeService.countAllStorages(curList, false);//总存款
	//	int comsum=incomeService.countCurCumsums(curList);//除加收外的消费当前的消费不包括以前付过的消费
		
		iUsed=iUsed+centAddpay;
		//int pay=storage-iUsed-iPayed;//应付
		//int pay =storage-iUsed+iPayed;
		msg.append("总存款:").append(Utils.toPrice(storage)).append("\n");
	    msg.append("总消费:").append(Utils.toPrice(iUsed)).append("\n");
	    msg.append("已付款:").append(Utils.toPrice(iPayed)).append("\n");
	   /* if(pay==0){
	    	msg.append("当前未欠款").append("\n");
	    }else if(pay>0){
	    	msg.append("当前余额:").append(Utils.toPrice(pay)).append("\n");
	    }else{
	    	msg.append("当前挂账:").append(Utils.toPrice(-pay)).append("\n");
	    }*/
	    msg.append("当前挂账:").append(Utils.toPrice(iUsed)).append("\n");
	    msg.append("退回押金:").append(Utils.toPrice(storage)).append("\n");
	    msg.append("确认挂账退房吗?");
	    if(UIUtils.confirm(msg.toString())){
	    	incomeService.hangUp(curList, add, vLable,unit,storage);
	    	okBtn.setDisabled(true);
	    }
		
	}
	/**是否有未归还的
	 * */
	public boolean isNoBorrow(List<Living> list){
		String r=null;
		List<TbLiveGoodsBorrow> noList =incomeService.isNoBorrow(list);
		if(noList==null){
			return true;
		}
		else{
			for(TbLiveGoodsBorrow b:noList){
				r=r+b.getLiving().getRoom().getName()+":"+b.getTbGoods().getName()+",";
			}
			UIUtils.alert(r);
			return false;
		}
	}
	public String getAutoLivingReMark(List<Living> list){
		String r="";
		for(Living l:list){
			int b=incomeService.querySingleConsum(l.getId(), true);
			r=r+l.getRoom().getName()+":消费:"+MoneyUtil.toString(b)+"\n";
		}
		return r;
	}
	public void queryProtocolUnit(String unitName,String conName){
		protocolUnitList.getItems().clear();
		List<ProtocolUnit> list =Services.getOtherBusiService().queryProtocolUnit(null, unitName, conName,true);
		if(list==null)
			return ;
		for(final ProtocolUnit u:list)
		{
			Listitem listitem = new Listitem();
			listitem.setValue(u.getId());
			listitem.setParent(protocolUnitList);
			listitem.appendChild(new Listcell(u.getCompany()));
			listitem.appendChild(new Listcell(u.getContactName()));
			listitem.addEventListener(Events.ON_CLICK, new EventListener() {
				
				@Override
				public void onEvent(Event event) throws Exception {
					// TODO Auto-generated method stub
					maxPrice.setValue(Utils.toPrice(u.getMaxPrice()));
					hangUpprice.setValue(Utils.toPrice(u.getPrice()));
				}
			});
		}
	}
	public List<Living> getSelectLive() {
		return selectLive;
	}
	public void setSelectLive(List<Living> selectLive) {
		this.selectLive = selectLive;
	}
	public Date getEarlyTime() {
		return earlyTime;
	}
	public void setEarlyTime(Date earlyTime) {
		this.earlyTime = earlyTime;
	}
	public Date getCheckTime() {
		return checkTime;
	}
	public void setCheckTime(Date checkTime) {
		this.checkTime = checkTime;
	}

}
